﻿
using System.Web;
using System.Text;
using System.IO;
using System;
using System.Security.Cryptography;
using System.Globalization;
using System.Configuration;
using System.Web.Security;
using System.Net;
namespace Yd.CommCls
{
    enum EBodyType : uint
    {
        EType_XML = 0,
        EType_JSON
    };
    public sealed class CommUtils
    {
        public const int _MiddlePage = 5;
        public const string _fielext = "";
        public const string _filepic = ",.jpg,.gif,.png,.jpeg,.bmp,.tiff";
        public static string _session = ConfigurationManager.AppSettings["issession"].Trim();
        public static string MD5key = ConfigurationManager.AppSettings["MD5key"].Trim();
        public static string MerNo = ConfigurationManager.AppSettings["MerNo"].Trim();
        public const int upfilelen = 2*1024*1024;

        private static string m_restAddress = "api.ucpaas.com";
        private static string m_restPort = "443";
        private static string m_mainAccount = "87b9c90efd1de249b574ff7f71c19992";
        private static string m_mainToken = "e509f4fc88a6c1b09de3ff0028a30dec";
        private static string m_appId = "427a412691e04b4c95d06ad6649a9972";
        private static bool m_isWriteLog = false;

        private static EBodyType m_bodyType = EBodyType.EType_JSON;
        /// <summary>
        /// 云之讯服务器api版本
        /// </summary>
        const string softVer = "2014-06-30";

        private static char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

        public static Random rd = new Random();
        public static string pxkt_GetCharFont(int strLength=30)
        {
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
            for (int i = 0; i < strLength; i++)
            {
                newRandom.Append(constant[rd.Next(62)]);
            }
            return newRandom.ToString();
        }

        /// <summary>
        /// 抓取html页面
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static void gethtml(string id)
        {
            for (int i = 0; i <= 20; i++)
            {
                try
                {
                    string url = "http://www.51e3.com/ShowNews.aspx?Id=" + id;
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                    req.Method = "GET";
                    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0";
                    using (WebResponse wr = req.GetResponse())
                    {
                        Stream ReceiveStream = wr.GetResponseStream();
                        StreamReader sr = new StreamReader(ReceiveStream, System.Text.Encoding.GetEncoding("gb2312"));
                        string resultstring = sr.ReadToEnd();
                        string fileName = "/html/" + id + ".html";
                        //if (File.Exists(HttpContext.Current.Server.MapPath(fileName)))
                        //{
                        //    File.Delete(HttpContext.Current.Server.MapPath(fileName));
                        //}
                        FileStream rFile = File.Create(HttpContext.Current.Server.MapPath(fileName));
                        StreamWriter writer = new StreamWriter(rFile, Encoding.GetEncoding("gb2312"));
                        writer.Write(resultstring.ToString());
                        writer.Flush();
                        writer.Close();
                        break;
                    }
                }
                catch
                { }
            }
        }

        /// <summary>
        /// http://localhost/scfx.aspx?Page=2
        /// </summary>
        /// <param name="id"></param>
        public static void gethtmlPage(string id)
        {
            for (int i = 0; i <= 20; i++)
            {
                try
                {
                    string url = "http://www.51e3.com/scfx.aspx?Page=" + id;
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                    req.Method = "GET";
                    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0";
                    using (WebResponse wr = req.GetResponse())
                    {
                        Stream ReceiveStream = wr.GetResponseStream();
                        StreamReader sr = new StreamReader(ReceiveStream, System.Text.Encoding.GetEncoding("gb2312"));
                        string resultstring = sr.ReadToEnd();
                        string fileName = "/html/scfx-" + id + ".html";
                        //if (File.Exists(HttpContext.Current.Server.MapPath(fileName)))
                        //{
                        //    File.Delete(HttpContext.Current.Server.MapPath(fileName));
                        //}
                        FileStream rFile = File.Create(HttpContext.Current.Server.MapPath(fileName));
                        StreamWriter writer = new StreamWriter(rFile, Encoding.GetEncoding("gb2312"));
                        writer.Write(resultstring.ToString());
                        writer.Flush();
                        writer.Close();
                        break;
                    }
                }
                catch
                { }
            }
        }

        /// <summary>
        /// 发送手机信息
        /// </summary>
        /// <param name="fmobile"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string SendMsg(string fmobile,string msg)
        {
            for (int i = 0; i < 5; i++)
            {
                string s = System.Web.HttpUtility.UrlEncode(msg, System.Text.UnicodeEncoding.GetEncoding("GB2312"));
                string fasong = "http://202.91.244.252/qd/SMSSendYD?usr=" + ConfigurationManager.AppSettings["mobilename"].Trim() + "&pwd=" + ConfigurationManager.AppSettings["mobilepwd"].Trim() + "&mobile=" + fmobile + "&sms=" + s;
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(fasong);
                req.Method = "GET";
                using (WebResponse wr = req.GetResponse())
                {
                    Stream ReceiveStream = wr.GetResponseStream();
                    StreamReader sr = new StreamReader(ReceiveStream, System.Text.Encoding.GetEncoding("gb2312"));
                    string resultstring = sr.ReadToEnd();
                    string[] ss = resultstring.Split(new char[] { ',' });
                    if (ss[0]=="0")
                    {
                        //成功
                        break;
                    }
                }
            }
            return "";
        }

        //云之讯发送短信
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="to">短信接收端手机号码</param>
        /// <param name="templateId">短信模板ID</param>
        /// <param name="param">内容数据，用于替换模板中{数字}</param>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        /// <exception cref="Exception"></exception>
        /// <returns>包体内容</returns>
        public static string SendSMS(string to, string templateId, string param)
        {

            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            if (templateId == null)
            {
                throw new ArgumentNullException("templateId");
            }

            try
            {
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");

                // 构建URL内容
                string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
                string uriStr;
                string xml = (m_bodyType == EBodyType.EType_XML ? ".xml" : "");
                uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/Messages/templateSMS{4}?sig={5}", m_restAddress, m_restPort, softVer, m_mainAccount, xml, sigstr);

                Uri address = new Uri(uriStr);

                WriteLog("SendSMS url = " + uriStr);

                // 创建网络请求  
                HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
                setCertificateValidationCallBack();

                // 构建Head
                request.Method = "POST";

                Encoding myEncoding = Encoding.GetEncoding("utf-8");
                byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
                string authStr = Convert.ToBase64String(myByte);
                request.Headers.Add("Authorization", authStr);


                // 构建Body
                StringBuilder data = new StringBuilder();

                if (m_bodyType == EBodyType.EType_XML)
                {
                    request.Accept = "application/xml";
                    request.ContentType = "application/xml;charset=utf-8";

                    data.Append("<?xml version='1.0' encoding='utf-8'?><templateSMS>");
                    data.Append("<appId>").Append(m_appId).Append("</appId>");
                    data.Append("<templateId>").Append(templateId).Append("</templateId>");
                    data.Append("<to>").Append(to).Append("</to>");
                    data.Append("<param>").Append(param).Append("</param>");
                    data.Append("</templateSMS>");
                }
                else
                {
                    request.Accept = "application/json";
                    request.ContentType = "application/json;charset=utf-8";

                    data.Append("{");
                    data.Append("\"templateSMS\":{");
                    data.Append("\"appId\":\"").Append(m_appId).Append("\"");
                    data.Append(",\"templateId\":\"").Append(templateId).Append("\"");
                    data.Append(",\"to\":\"").Append(to).Append("\"");
                    data.Append(",\"param\":\"").Append(param).Append("\"");
                    data.Append("}}");
                }

                byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

                WriteLog("CreateSubAccount requestBody = " + data.ToString());

                // 开始请求
                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(byteData, 0, byteData.Length);
                }

                // 获取请求
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream  
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string responseStr = reader.ReadToEnd();

                    WriteLog("CreateSubAccount responseBody = " + responseStr);

                    if (responseStr != null && responseStr.Length > 0)
                    {
                        return responseStr;
                    }
                }
                return null;
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        /// <summary>
        /// 订单号
        /// </summary>
        /// <returns></returns>
        public static string GetOrderNum()
        {
            return Guid.NewGuid().ToString("D").Replace("-", "");
            //string code = "P{0}";
            //if (GetUserId() != "0")
            //{
            //    code = GetUserId() + constant[rd.Next(62)] + "{0}" + constant[rd.Next(62)];
            //}
            //string _num = pxkt_GetCharFont();
            //return string.Format(code, _num);
        }

        /// <summary>
        /// 获取系统的GUID
        /// </summary>
        /// <param name="_format"></param>
        /// <returns></returns>
        public static string GetGuid(string _format = "D")
        {
            return Guid.NewGuid().ToString(_format).Replace("-","");
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="name"></param>
        /// <param name="role"></param>
        public static void WriteCookeLogin(string userid, string UserName)
        {
            if (_session=="0")
            {
                HttpContext.Current.Response.Cookies["Uid"].Value = userid;
                HttpContext.Current.Response.Cookies["Uid"].Expires = DateTime.Now.AddHours(5);
                HttpContext.Current.Response.Cookies["UserName"].Value = HttpUtility.UrlEncode(UserName);
                HttpContext.Current.Response.Cookies["UserName"].Expires = DateTime.Now.AddHours(5);
            }
            else
            {
                HttpContext.Current.Session["Uid"] = userid.Trim();
                HttpContext.Current.Session["UserName"] = UserName.Trim();
            }
        }

        public static void WriteCookeLoginAdmin(string userid, string UserName)
        {
            if (_session == "0")
            {
                HttpContext.Current.Response.Cookies["AUid"].Value = userid;
                HttpContext.Current.Response.Cookies["AUid"].Expires = DateTime.Now.AddHours(5);
                HttpContext.Current.Response.Cookies["AUserName"].Value = HttpUtility.UrlEncode(UserName);
                HttpContext.Current.Response.Cookies["AUserName"].Expires = DateTime.Now.AddHours(5);
            }
            else
            {
                HttpContext.Current.Session["AUid"] = userid.Trim();
                HttpContext.Current.Session["AUserName"] = UserName.Trim();
            }
        }


        /// <summary>
        /// 清楚COOKIES
        /// </summary>
        public static void ClearCookie()
        {
            try
            {
                if (_session == "0")
                {

                    HttpContext.Current.Request.Cookies["Uid"].Expires = DateTime.Now.AddHours(-1);
                    HttpContext.Current.Response.Cookies.Add(HttpContext.Current.Request.Cookies["Uid"]);
                    HttpContext.Current.Request.Cookies["UserName"].Expires = DateTime.Now.AddHours(-1);
                    HttpContext.Current.Response.Cookies.Add(HttpContext.Current.Request.Cookies["UserName"]);
                }
                else
                {
                    HttpContext.Current.Session.Abandon();
                }
            }
            catch { }
        }

        public static void ClearCookieA()
        {
            try
            {
                if (_session == "0")
                {

                    HttpContext.Current.Request.Cookies["AUid"].Expires = DateTime.Now.AddHours(-1);
                    HttpContext.Current.Response.Cookies.Add(HttpContext.Current.Request.Cookies["AUid"]);
                    HttpContext.Current.Request.Cookies["AUserName"].Expires = DateTime.Now.AddHours(-1);
                    HttpContext.Current.Response.Cookies.Add(HttpContext.Current.Request.Cookies["AUserName"]);
                }
                else
                {
                    HttpContext.Current.Session.Abandon();
                }
            }
            catch { }
        }

        public static string GetUserIdA()
        {
            if (_session == "0")
            {
                return HttpContext.Current.Request.Cookies["AUid"] != null ? HttpContext.Current.Request.Cookies["AUid"].Value : "0";
            }
            else
            {
                return HttpContext.Current.Session["AUid"] != null ? HttpContext.Current.Session["AUid"].ToString().Trim() : "0";
            }
        }

        public static string GetUserNameA()
        {
            if (_session == "0")
            {
                return HttpContext.Current.Request.Cookies["AUserName"] != null ? HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["AUserName"].Value) : "";
            }
            else
            {
                return HttpContext.Current.Session["AUserName"] != null ? HttpContext.Current.Session["AUserName"].ToString().Trim() : "";
            }
        }

        /// <summary>
        /// 获取登录用户的编号
        /// </summary>
        /// <returns></returns>
        public static string GetUserId()
        {
            if (_session == "0")
            {
                return HttpContext.Current.Request.Cookies["Uid"] != null ? HttpContext.Current.Request.Cookies["Uid"].Value : "0";
            }
            else
            {
                return HttpContext.Current.Session["Uid"] != null ? HttpContext.Current.Session["Uid"].ToString().Trim() : "0";
            }
        }

        public static string GetUserName()
        {
            if (_session == "0")
            {
                return HttpContext.Current.Request.Cookies["UserName"] != null ? HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserName"].Value) : "";
            }
            else
            {
                return HttpContext.Current.Session["UserName"] != null ? HttpContext.Current.Session["UserName"].ToString().Trim() : "";
            }
        }

        public static string ChineseByEnWeek(DateTime dt) { switch (dt.DayOfWeek.ToString()) { case "Monday": return "星期一"; case "Tuesday": return "星期二"; case "Wednesday": return "星期三"; case "Thursday": return "星期四"; case "Friday": return "星期五"; case "Saturday": return "星期六"; case "Sunday": return "星期日"; default: return ""; } }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_path"></param>
        /// <returns></returns>
        public static bool DelUpFile(string _path)
        {
            if (string.IsNullOrEmpty(_path.Trim()))
            {
                return true;
            }
            string ext = _path.Substring(_path.LastIndexOf(".") + 1);
            if (File.Exists(HttpContext.Current.Server.MapPath(_path.Trim())))
            {
                File.Delete(HttpContext.Current.Server.MapPath(_path.Trim()));
            }
            else
            {
                return false;
            }

            string fileExt = Path.GetExtension(_path).ToLower();
            if (File.Exists(HttpContext.Current.Server.MapPath(_path.Trim().Replace(fileExt, "_s" + fileExt))))
            {
                File.Delete(HttpContext.Current.Server.MapPath(_path.Trim().Replace(fileExt, "_s" + fileExt)));
            }

            if (ext.ToLower().Trim() == "pdf")
            {
                if (File.Exists(HttpContext.Current.Server.MapPath(_path.Trim().Replace(".pdf",".swf"))))
                {
                    File.Delete(HttpContext.Current.Server.MapPath(_path.Trim().Replace(".pdf", ".swf")));
                }
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="upfiles"></param>
        /// <param name="ltal"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string UpfilePic(HttpPostedFile imgFile, string _fileexts, string path = "../Uploadfiles/Images/")
        {
            if (imgFile.ContentLength > upfilelen)
            {
                return "图片大小不正确不能超过2M";
            }
            string filename = "";
            if (imgFile!=null)
            {
                string fileName = imgFile.FileName;

                


                string fileExt = Path.GetExtension(fileName).ToLower();
                if (!string.IsNullOrEmpty(_fileexts.Trim()))
                {
                    if (_fileexts.Trim().ToLower().IndexOf("," + fileExt.Trim() + ",") == -1)
                    {
                        return "图片格式不正确";
                    }
                }

                string dirPath = HttpContext.Current.Server.MapPath(path);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }


                string pdffilename = "";
                if (_filepic.ToLower().Trim().IndexOf("," + fileExt.Trim() + ",") != -1)
                {
                    pdffilename = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
                }
                else
                    pdffilename = Path.GetFileName(fileName).Trim().Replace(fileExt, "");
                
                string newFileName = pdffilename + fileExt;
                filename = path + newFileName;
                imgFile.SaveAs(dirPath + newFileName);
                if (_filepic.ToLower().Trim().IndexOf("," + fileExt.Trim() + ",") != -1)
                {
                    //SaveThumb(dirPath + newFileName, 415, 230);
                    //图片压缩
                }
                return filename.Trim();
            }
            return "";
        }


        public static string Upfilesoft(HttpPostedFile imgFile, string _fileexts, string path = "../Uploadfiles/Images/")
        {
            string filename = "";
            if (imgFile != null)
            {
                string fileName = imgFile.FileName;
                string fileExt = Path.GetExtension(fileName).ToLower();
                //if (!string.IsNullOrEmpty(_fileexts.Trim()))
                //{
                //    if (_fileexts.Trim().ToLower().IndexOf("," + fileExt.Trim() + ",") == -1)
                //    {
                //        return "";
                //    }
                //}
                string dirPath = HttpContext.Current.Server.MapPath(path);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }


                string pdffilename = "";
                //if (_filepic.ToLower().Trim().IndexOf("," + fileExt.Trim() + ",") != -1)
                //{
                    pdffilename = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
                //}
                //else
                //    pdffilename = Path.GetFileName(fileName).Trim().Replace(fileExt, "");

                string newFileName = pdffilename + fileExt;
                filename = path + newFileName;
                imgFile.SaveAs(dirPath + newFileName);
                //if (_filepic.ToLower().Trim().IndexOf("," + fileExt.Trim() + ",") != -1)
                //{
                //    SaveThumb(dirPath + newFileName, 415, 230);
                //    //图片压缩
                //}
                return filename.Trim();
            }
            return "";
        }

     
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="paths"></param>
        public static void SaveThumb(string paths, int widths = 451, int heights = 230)
        {
            try
            {
                string fileExt = Path.GetExtension(paths).ToLower();


                MakeThumbnail(paths, paths.Replace(fileExt, "_s" + fileExt), widths, heights, "DB", fileExt.ToUpper().Replace(".", ""));

                //System.Drawing.Image srcImg = System.Drawing.Image.FromFile(paths);
                //Bitmap thumbImg = new Bitmap(widths, heights);
                //Graphics graphics = Graphics.FromImage(thumbImg);
                //thumbImg.SetResolution(srcImg.HorizontalResolution, srcImg.VerticalResolution); // 加上每 DPI（每英寸的点数），更精确。 
                //graphics.DrawImage(srcImg, 0, 0, thumbImg.Width, thumbImg.Height);
                //thumbImg.Save(paths.Replace(fileExt, "_s" + fileExt));
                //graphics.Dispose();
                //thumbImg.Dispose();
                //srcImg.Dispose();

                //Bitmap bmpDest = new Bitmap(360, 270); 
                //Bitmap bmpSrc = new Bitmap("Source.jpg"); 
                //Graphics g = Graphics.FromImage(bmpDest); 
                //g.DrawImage(bmpSrc, rectDest, rectSrc, GraphicsUnit.Pixel); 

            }
            catch { };
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param> 
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, string type)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形） 
                    break;
                case "W"://指定宽，高按比例 
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形） 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                case "DB"://等比缩放（不变形，如果高大按高，宽大按宽缩放） 
                    //if ((double)originalImage.Width / (double)towidth < (double)originalImage.Height / (double)toheight)
                    //{
                    //    toheight = height;
                    //    towidth = originalImage.Width * height / originalImage.Height;
                    //}
                    //else
                    //{
                        towidth = width;
                        toheight =originalImage.Height * width / originalImage.Width;
                    //}
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //保存缩略图
                if (type == "JPG")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                if (type == "BMP")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
                }
                if (type == "GIF")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
                }
                if (type == "PNG")
                {
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Fstr"></param>
        /// <param name="_len"></param>
        /// <returns></returns>
        public static string CutString(string Fstr, int _len)
        {
            if (Fstr.Length > _len)
            {
                return Fstr.Substring(0, _len) + "...";
            }
            return Fstr;
        }

        public static string ParseTags(string HTMLStr)
        {
            return System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", "");
        }

       
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetMd5(string str, int code = 32)
        {
            if (code == 16)
            {
                return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToUpper().Substring(8, 16);
            }
            else
            {
                return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToUpper();
            }
        }

        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptDES(string pToEncrypt, string sKey)
        {
            try
            {
                if (sKey.Trim() == "")
                {
                    sKey = "md!@#3zha1n2g";
                }
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                ret.ToString();
                return ret.ToString();
            }
            catch
            {
                return pToEncrypt.Trim();
            }
        }

        public static string GetClientIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }

       
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptDES(string pToDecrypt, string sKey)
        {
            try
            {
                if (sKey.Trim() == "")
                {
                    sKey = "md!@#3zha1n2g";
                }
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
            catch
            {
                return pToDecrypt.Trim();
            }
        }

         /// <summary>
        ///  证书验证回调函数  
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cer"></param>
        /// <param name="chain"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool CertificateValidationResult(object obj, System.Security.Cryptography.X509Certificates.X509Certificate cer, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
        {
            return true;
        }
        /// <summary>
        /// 设置服务器证书验证回调
        /// </summary>
        public static void setCertificateValidationCallBack()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = CertificateValidationResult;
        }

        /// <summary>
        /// 获取日志路径
        /// </summary>
        /// <returns>日志路径</returns>
        public static string GetLogPath()
        {
            string dllpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            dllpath = dllpath.Substring(8, dllpath.Length - 8);    // 8是 file:// 的长度
            return System.IO.Path.GetDirectoryName(dllpath) + "\\log.txt";
        }
        private static void WriteLog(string log)
        {
            if (m_isWriteLog)
            {
                string strFilePath = GetLogPath();
                System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
                sw.WriteLine(DateTime.Now.ToString() + "\t" + log);
                sw.Close();
                fs.Close();
            }
        }

        public static void getMonthWarmingClosingLine(int multiple, out double warmingLine, out double closingLine)
        {

            switch (multiple)
            {
                case 0:
                    warmingLine = 0.5;
                    closingLine = 0.4;
                    break;
                case 6:
                    warmingLine = 0.6;
                    closingLine = 0.5;
                    break;
                case 5:
                    warmingLine = 0.6;
                    closingLine = 0.5;
                    break;
                case 4:
                    warmingLine = 0.6;
                    closingLine = 0.5;
                    break;
                case 3:
                    warmingLine = 0.5;
                    closingLine = 0.4;
                    break;
                case 2:
                    warmingLine = 0.5;
                    closingLine = 0.4;
                    break;
                case 1:
                    warmingLine = 0.5;
                    closingLine = 0.4;
                    break;
                default:
                   warmingLine = 0.5;
                    closingLine = 0.4;
                    break;

            }
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="source">原内容</param>
        /// <returns>加密后内容</returns>
        public static string MD5Encrypt(string source)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            System.Security.Cryptography.MD5 md5Hasher = System.Security.Cryptography.MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(source));

            // Create a new Stringbuilder to collect the bytes and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("X2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
    }
}
